import Config from "./config";
import axios from 'axios';
import API from "@/api";
import { goRouter } from "./../index"
import { requestStore } from "@/store/request";
import { globalStore } from "@/store/global";
import {storage} from '@/utils'
const CancelToken = axios.CancelToken

let cancel;
const instance = axios.create(Config.options);

const errorFunction = function(response, tipConfig) {
    const requestVue = requestStore();
    const globalVue = globalStore();
    !requestVue.interceptShow && Config.tipShow(response, tipConfig, 'error');
    if(response.code == '406' && !requestVue.interceptShow) {
        // 判断登录是否过期，跳转登录页
        requestVue.setInterceptShow(true)
        globalVue.logout();
        goRouter('/login');
    };
    return response.data;
}
const successFunction = function(response, tipConfig) {
    const requestVue = requestStore();
    Config.tipShow(response.data, tipConfig, 'success');
    let urlArr = response.config.url.split('/');
    if (!arraysHaveIntersection(urlArr, Config.noInterceptArr)) {
        requestVue.setInterceptShow(false)
    }
    return response.data
}

const posUrl =  function(url) { /* 判断url是否为绝对路径 */
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
}

// 判断两个数组中是否有交集
function arraysHaveIntersection(arr1, arr2) {
    return arr1.some(value => arr2.includes(value));
}

instance.interceptors.request.use( 
    config => {
    config.cancelToken = new CancelToken((c) => {
        cancel = c
    })
    const requestVue = requestStore();
    const globalVue = globalStore();
    let token = globalVue.token || storage.getLocal('token') || '';
    // 是否拦截请求  true 拦截请求  false 正常请求
    let interceptShow = requestVue.interceptShow;  
    // 在发送请求之前做些什么    1. 判断url是否为绝对路径，
    if (!posUrl(config.url)) {
        const reqURL = config.url.split('.');
        if( reqURL.length == 2 ){
            config.url = API[reqURL[0]][reqURL[1]]
        }else if( reqURL.length == 3 ){
            config.url = API[reqURL[0]+'/'+reqURL[1]][reqURL[2]]
        }
        let urlArr = config.url.split('/');
        if (arraysHaveIntersection(urlArr, Config.noInterceptArr)) {
            interceptShow = false
        }
        
    }
    if (token) (interceptShow = false)
    if(interceptShow) {
        cancel('请求已取消')
    }
    let tipConfig = {};

    if(config.data && config.data.toString().indexOf('tipConfig') > -1){
        tipConfig = config.data.tipConfig;
        delete config.data.tipConfig;
    }
    if(config.tipConfig){
        tipConfig = config.tipConfig
    }
    config.tipConfig = tipConfig;

    if (config.tipConfig?.upLoadForm) {
        config.data = config.data.form
    }
    config.headers.token = token
    return config;
}, error => {
    cancel = null
    // console.log(error, '请求拦截失败');
    return Promise.reject(error);
});

instance.interceptors.response.use(function (response) {
    cancel = null
    let tipConfig = {...Config.tipConfig, ...response.config.tipConfig};
    if(tipConfig.codeFile){
        return successFunction(response,tipConfig) 
    }
    if(response.data.code == 200){
        return successFunction(response,tipConfig)
    }
    else{
        response['code'] = response.data.code;
        return errorFunction(response, tipConfig)
    }
}, function(error) {
    cancel = null
    return Promise.reject(error);
});

export default instance;
